package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.permissions

import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.IApiProcessCameroonCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.createApiActionCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.doPostRequestCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.login.LoginCameroonActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.user.mainProcessFormatCameroon
import org.json.JSONObject

class PermissionCameroonViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _checkResult = MutableLiveData<Boolean>()
    val checkResult: LiveData<Boolean> = _checkResult

    private val _grantedResult = MutableLiveData<PermissionCameroonGrantedResult>()
    val grantedResult: LiveData<PermissionCameroonGrantedResult> = _grantedResult

    private val _mainProcessResult = MutableLiveData<PermissionCameroonMainProcessResult>()
    val mainProcessResult: LiveData<PermissionCameroonMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<PermissionCameroonNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<PermissionCameroonNextRouterResult<AppCompatActivity>> =
        _nextRouterResult


    private var permissionCheckbox = true

    var displayPermission: String = "APPLIST"
    val indicatorDataList = mutableListOf<PermissionCameroonPager>()
    val pagerDataList = mutableListOf<PermissionCameroonPager>()

    /**
     * 更新checkbox
     */
    fun updateCheckbox() {
        permissionCheckbox = !permissionCheckbox
        _checkResult.value = permissionCheckbox
    }

    /** 查询主流程接口 */
    fun mainProcess() {
        // 判断是否已登录
        if (!ProjectApplication.onActionReady()) {
            _nextRouterResult.value =
                PermissionCameroonNextRouterResult(nextPage = LoginCameroonActivity::class.java)
            return
        }

        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = PermissionCameroonMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value =
                    PermissionCameroonMainProcessResult(error = errMsg)
            }
        })
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormatCameroon()
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                PermissionCameroonNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }

    /**
     * 开始操作同意
     */
    fun startPermissionGranted() {
        if (permissionCheckbox) {
            if (displayPermission.contains("APPLIST", true)) {
                val nextIndicator = checkNextIndicator(displayPermission)
                _grantedResult.value =
                    PermissionCameroonGrantedResult(
                        agree = true,
                        permission = displayPermission,
                        nextIndicator = nextIndicator
                    )
            } else {
                if (checkPermissionsGranted(mutableListOf(displayPermission))) {
                    val nextIndicator = checkNextIndicator(displayPermission)
                    _grantedResult.value =
                        PermissionCameroonGrantedResult(
                            agree = true,
                            permission = displayPermission,
                            nextIndicator = nextIndicator
                        )
                } else {
                    _grantedResult.value =
                        PermissionCameroonGrantedResult(
                            start = true,
                            permission = displayPermission
                        )
                }
            }
        } else {
            _grantedResult.value =
                PermissionCameroonGrantedResult(ask = true, permission = displayPermission)
        }
    }

    /**
     * 点击拒绝、同意
     */
    fun grantedResult(agree: Boolean) {
        // 更新页面显示
        val permission = displayPermission
        val ask = false
        val start = false

        var nextIndicator: Int? = null
        for (index in 0 until indicatorDataList.size) {
            val item = indicatorDataList[index]
            if (item.permission.contains(permission, true)) {
                val nextIndex = index + 1
                if (indicatorDataList.size > nextIndex) {
                    nextIndicator = nextIndex
                }
                break
            }
        }

        if (nextIndicator == null) {
            for (index in 0 until indicatorDataList.size) {
                val item = indicatorDataList[index]
                if ((item.optResult == OPT_SPLASH_RESULT_NONE) and
                    (!item.permission.contains("APP", true))
                ) {
                    nextIndicator = index
                    break
                }
            }
        }

        _grantedResult.value =
            PermissionCameroonGrantedResult(
                ask = ask,
                start = start,
                agree = agree,
                reject = !agree,
                permission = permission,
                nextIndicator = nextIndicator
            )

        // 判断权限是否全部同意
        val allPermissions = mutableListOf(
            android.Manifest.permission.READ_SMS,
            android.Manifest.permission.READ_PHONE_STATE
        )
        if (checkPermissionsGranted(allPermissions)) {
            mainProcess()
        }
    }

    /**
     * 开始操作同意
     */
    private fun checkNextIndicator(permission: String): Int? {
        var nextIndicator: Int? = null
        for (index in 0 until indicatorDataList.size) {
            val item = indicatorDataList[index]
            if (item.permission.contains(permission, true)) {
                val nextIndex = index + 1
                if (indicatorDataList.size > nextIndex) {
                    nextIndicator = nextIndex
                }
                break
            }
        }
        return nextIndicator
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                ProjectApplication.instance,
                it
            )
        }
        return !isNotAllGranted
    }
}